<template>
  <div>
    <slot name="left"></slot>
    <span :id="eleId" :class="classArr" ref="number"></span>
    <slot name="right"></slot>
  </div>
</template>
<script>
import CountUp from 'countup'
export default {
  name: 'count_t',
  data(){
    return {
      counter: {}
    }
  },
  computed: {
    eleId(){
      // 每个组件都有自己的uid 是全局唯一的
      return `count_up_${this._uid}`
    },
    classArr(){
      return [
        'count-default',
        this.className
      ]
    }
  },
  methods:{
     getNumber() {
      return this.$refs.number.innerHTML
    },
    endFun(){
      setTimeout(() =>{
        this.$nextTick(() =>{
          this.$emit("sjf",Number(this.getNumber().replace(',','')))
          console.log('触发了')
        })
      },this.duration*1000+5)
    }
  },
  watch: {
    endVal (newV,oldV){
      this.counter.update(newV)
      this.endFun()
    }
  },

  props: {
    startVal:{
      type:Number,
      default: 0
    },
    endVal: {
      type:Number,
      required: true,
      default: 100
    },
    decimal: {
      // 保留小数点位数
      type:Number,
      default: 0
    },
    duration: {
      // 动画时间  单位秒
      type:Number,
      default: 1
    },
    useEasing: {
      // 是否由慢到快
      type: Boolean,
      default: false
    },
    useGrouping: {
      type: Boolean,
      default:true
    },
    className: {
      type: String,
      default: ''
    }
  },
  mounted() {
    // dom元素渲染完成后调用
    this.$nextTick( ()=>{
      this.counter = new CountUp(this.eleId, this.startVal, this.endVal, this.decimal, this.duration, {
        useEasing: this.useEasing,
        useGrouping: this.useGrouping,
        separator: ',',
        decimal: '.'
      })
      this.counter.start()
      setTimeout(() =>{
        this.endFun() 
      },4)
    })
  }
}
</script>
<style scoped>
  .count-default{
    color: red;
  }
</style>


